<template>
  <div class="course-section">
    <div class="titleHeader">
      <div>
        <el-page-header @back="goBack" :content="titleDetail">
        </el-page-header>
      </div>
      <el-button type="primary" @click="addSection">添加章节</el-button>
    </div>
    <el-card>
      <el-tree :data="sections" :expand-on-click-node='false' draggable :props="defaultProps"
       :allow-drop="handleAllowDrop"
       @node-click="handleNodeClick"
       @node-drop="handleNodeDrop"
       v-loading="isLoading"
       >
        <div class="inner" slot-scope="{node, data}">
            <!-- 内容设置 -->
            <span>{{ node.label }}</span>
            <!-- 后续按钮操作 -->
            <span v-if="data.sectionName" class="actions">
                <el-button @click="editSection(data)">编辑</el-button>
                <el-button  type="primary" @click="addLesson(data)">添加课时</el-button>
                <el-button @click="editStatusMethod(data, 1)">状态</el-button>
            </span>
            <span v-else class="actions">
                <el-button @click="editLesson(data)">编辑</el-button>
                <el-button type="success" @click="$router.push({
                  name: 'course-video',
                  params: {
                    courseId
                  },
                  query: {
                    lessonId: data.id
                  }
                })">上传视频</el-button>
                <el-button @click="editStatusMethod(data, 2)">状态</el-button>
            </span>
        </div>
      </el-tree>
    </el-card>
    <!-- 创建或编辑section -->
    <el-dialog
        title="提示"
        :visible.sync="dialogVisible"
        width="50%">
        <section-create-or-editor :isEditor="isEditor"
          @handleClose="handleClose"
          :courseId="courseId"
          :courseName="course.courseName"
          :sectionId="editSectionId"
          ></section-create-or-editor>
    </el-dialog>
    <el-dialog title="提示"
        :visible.sync="addVisible"
        width="50%">
      <addLesson :courseId='addCourseId' :sectionId="addSectionId" @handleVisiable="handleVisiable"></addLesson>
    </el-dialog>
    <!-- 编辑课程 -->
    <el-dialog
        title="提示"
        :visible.sync="editLessonVisible"
        width="50%">
      <editLesson @handleEditLessonVisiable="handleEditLessonVisiable" :editLessonId="editLessonId"></editLesson>
    </el-dialog>
    <!-- 编辑状态 -->
    <el-dialog
        title="状态修改"
        :visible.sync="statusVisible"
        width="50%">
      <el-form ref="form" :model="editStatus" label-width="100px">
        <el-form-item label="状态变更：">
          <el-select v-model="editStatus.entity.status" placeholder="请选择状态">
            <el-option label="隐藏" :value="2"></el-option>
            <el-option label="待更新" :value="1"></el-option>
            <el-option label="已更新" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <div class="btnGroup">
            <el-button>取消</el-button>
            <el-button type="primary" @click="updateStatus">更新</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { getSectionAndLesson, saveOrUpdateLesson, saveOrUpdateSection } from '@/services/course-section.js'
import sectionCreateOrEditor from './components/sectionCreateOrEditor.vue'
import addLesson from './components/addLesson.vue'
import editLesson from './components/editLesson.vue'
import { getCourseById } from '@/services/course.js'

export default {
  name: 'course-section',
  components: {
    sectionCreateOrEditor,
    addLesson,
    editLesson
  },
  props: {
    courseId: {
      type: [String, Number],
      require: true
    }
  },
  data () {
    return {
      editStatus: {
        type: 0,
        entity: {

        }
      },
      statusVisible: false,
      editLessonId: null,
      addCourseId: null,
      addSectionId: null,
      addVisible: false,
      editLessonVisible: false,
      isLoading: false,
      editSectionId: null,
      isEditor: false,
      dialogVisible: false,
      titleDetail: '32131',
      sections: [],
      course: {},
      defaultProps: {
        children: 'lessonDTOS',
        // label: 'sectionName'
        label (data) {
          // data是章节或课时的时候，label的属性名不同，需要检测后使用
          return data.sectionName || data.theme
        }
      }
    }
  },
  methods: {
    async updateStatus () {
      console.log(this.editStatus)
      // section状态
      if (this.editStatus.type === 1) {
        const { data } = await saveOrUpdateSection(this.editStatus.entity)
        // console.log(data)
        if (data.code === '000000') {
          this.$message.success('更新成功')
          this.statusVisible = false
        }
      } else {
        // lesson状态
        const entity = this.editStatus.entity
        const lesson = {
          id: entity.id,
          courseId: entity.courseId,
          sectionId: entity.sectionId,
          theme: entity.theme,
          duration: entity.duration,
          isFree: entity.isFree,
          orderNum: entity.orderNum,
          status: entity.status
        }
        const { data } = await saveOrUpdateLesson(lesson)
        // console.log(data)
        if (data.code === '000000') {
          this.$message.success('更新成功')
          this.statusVisible = false
        }
      }
    },
    editStatusMethod (data, type) {
      console.log(data, type)
      this.statusVisible = true
      console.log(data)
      // section编辑
      this.editStatus = {
        type: type,
        entity: data
      }
      console.log(this.editStatus)
    },
    handleEditLessonVisiable (type) {
      this.editLessonVisible = false
      if (type === 1) {
        this.loadData()
      }
    },
    editLesson (lesson) {
      console.log('lesson=======', lesson)
      this.editLessonVisible = true
      this.editLessonId = lesson.id
    },
    handleVisiable (type) {
      this.addVisible = false
      if (type === 1) {
        this.loadData()
      }
    },
    goBack () {
      this.$router.go(-1)
    },
    handleNodeClick (data) {
      console.log(data);
    },
    addLesson (data) {
      this.addVisible = true
      console.log(data)
      this.addCourseId = data.courseId
      this.addSectionId = data.id
    },
    editSection (data) {
      this.isEditor = true
      this.dialogVisible = true
      this.editSectionId = data.id
    },
    handleClose (type) {
      console.log(type)
      this.dialogVisible = false
      if (type === 1) {
        // 列表刷新
        this.loadData()
      }
    },
    addSection () {
      this.isEditor = false
      this.dialogVisible = true
    },
    async loadData () {
      const data1 = await getCourseById(this.courseId)
      this.course = data1.data.data
      this.titleDetail = this.course.courseName
      // console.log('data1.data', data1.data.data)
      const { data } = await getSectionAndLesson(this.courseId)
      console.log(data)
      if (data.code === '000000') {
        this.sections = data.data
      }
    },
    // 节点拖拽处理函数
    handleAllowDrop (draggingNode, deopNode, type) {
      // 规则1：只能同级移动，type不能为inner
      // 规则2：课时不能移动到其他章节中
      return type !== 'inner' && draggingNode.data.sectionId === deopNode.data.sectionId
    },
    // 节点拖拽完毕后的处理函数
    async handleNodeDrop (draggingNode, dropNode, type, event) {
      this.isLoading = true
      // 由于有很多章节和课时，需要给每个章节和课时都进行最新的排序的请求
      try {
        await Promise.all(dropNode.parent.childNodes.map(async (item, index) => {
        //   判断当前是章节还是课时，
          if (draggingNode.data.sectionId) {
            // 课时
            return await saveOrUpdateLesson({
              id: item.data.id,
              orderNum: index
            })
          } else {
            return await saveOrUpdateSection({
              id: item.data.id,
              orderNum: index
            })
          }
        }))
        this.$message.success('更新成功')
      } catch (err) {
        this.$message.error('数据更新失败', err)
      }
      this.isLoading = false
    }
  },
  created () {
    this.loadData()
  }
}
</script>

<style>
.el-tree-node__content{
  height: 60px;
}
.inner{
  flex: 1;
  display: flex;
  justify-content: space-between;
  padding: 10px;
  align-items: center;
  border-bottom: 1px solid #ebeef5;
}
.titleHeader{
  margin-bottom: 10px;
  display: flex;
  justify-content: space-between;
}
.btnGroup{
  text-align: left;
}
</style>
